from ..exception.TestException import TestException
from ..common.ui.PageElement import PageElement
from ..exception.errorcode import ErrorCode


class SwitchButton(PageElement):

    def getValue(self):
        self.wait_element_presence()
        script = "return $(arguments[0]).switchbutton('option','state')"
        values = self._execute_script(script, self._get_web_element())
        return values

    def setValue(self, value:str = None):
        self.wait_element_presence()
        current_value = self.getValue()
        set_value = None
        if value is None:
            set_value = 'true' if bool(1-current_value) else 'false'
        else:
            if value.upper() == 'ON' or value == '开' or value == '启用':
                set_value = 'true'
            elif value.upper() == 'OFF' or value == '关' or value == '禁用':
                set_value = 'false'
            else:
                raise TestException.by_error_code(ErrorCode.SWITCH_BUTTON_NOT_SUPPORT_VALUE, value=value)

        if set_value != current_value:
            script = "$(arguments[0]).switchbutton('option','state', {value})".format(value = set_value)
            self._execute_script(script, self._get_web_element())

    def get_identification(self):
        identification = {'data-ui-role': ['switchbutton']}
        return identification

